<template>
    <div class="trace-container">
      <!-- 统计指标卡片 -->
      <div class="dashboard-cards">
        <el-card class="stat-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon process"></div>
            <div class="card-text">
              <div class="card-title">总生产批次</div>
              <div class="card-value">{{ totalBatches }}</div>
            </div>
          </div>
        </el-card>
        <el-card class="stat-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon quality"></div>
            <div class="card-text">
              <div class="card-title">质检合格率</div>
              <div class="card-value">{{ qualifiedRate }}%</div>
            </div>
          </div>
        </el-card>
        <el-card class="stat-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon alert"></div>
            <div class="card-text">
              <div class="card-title">待处理异常</div>
              <div class="card-value">{{ pendingIssues }}</div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 增强型搜索栏 -->
      <div class="advanced-search">
        <el-form :inline="true">
          <el-form-item label="产品ID">
            <el-input
              v-model="searchParams.productId"
              placeholder="输入产品ID"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="生产环节">
            <el-select
              v-model="searchParams.processTypes"
              multiple
              collapse-tags
              placeholder="选择环节"
            >
              <el-option
                v-for="item in processOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="日期范围">
            <el-date-picker
              v-model="searchParams.dateRange"
              type="daterange"
              value-format="YYYY-MM-DD"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>查询
            </el-button>
            <el-button @click="handleExport">
              <el-icon><Download /></el-icon>导出
            </el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-card class="data-table">
        <el-table
          :data="pagedData"
          border
          stripe
          height="400px"
          highlight-current-row
          v-loading="loading"
          @sort-change="handleSortChange"
        >
          <el-table-column prop="productId" label="产品ID" min-width="13%" sortable />
          <el-table-column prop="batchNo" label="批次号" min-width="9%" sortable />
          <el-table-column prop="processType" label="生产环节" min-width="7%">
            <template #default="{ row }">
              <div class="process-tag">
                <span class="tag-icon">{{ processIcons[row.processType as keyof typeof processIcons] }}</span>
                {{ processTypeMap[row.processType as keyof typeof processTypeMap] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="location" label="生产地点" min-width="10%" />
          <el-table-column prop="processTime" label="操作时间" min-width="8%" sortable />
          <el-table-column prop="operator" label="负责人" min-width="7%" />
          <el-table-column prop="inspector" label="质检员" min-width="7%" />
          <el-table-column prop="status" label="质检状态" min-width="7%">
            <template #default="{ row }">
              <div class="quality-status" :class="row.status">
                <span class="status-dot"></span>
                {{ statusMap[row.status as keyof typeof statusMap] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="环境数据" min-width="7%">
            <template #default="{ row }">
              <div class="env-data">
                <el-tooltip content="温度">
                  <span class="env-item">🌡️ {{ row.temperature }}</span>
                </el-tooltip>
                <el-tooltip content="湿度">
                  <span class="env-item">💧 {{ row.humidity }}</span>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="7%" fixed="right">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                plain
                @click="showQRDialog(row)"
              >
                <el-icon><Camera /></el-icon>溯源码
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="filteredData.length"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :pager-count="7"
            background
            prev-text="上一页"
            next-text="下一页"
            total-text="总计"
            :popper-props="{
              popperOptions: {
                modifiers: [{ name: 'offset', options: { offset: [0, 10] } }]
              }
            }"
          />
        </div>
      </el-card>

      <!-- 增强型二维码弹窗 -->
      <el-dialog
        v-model="qrDialog.visible"
        :title="`产品溯源网页二维码`"
        width="1400px"
        destroy-on-close
        class="trace-dialog"
        :close-on-click-modal="false"
        :close-on-press-escape="true"
      >
        <div v-if="qrDialog.data" class="qr-dialog-content">
          <!-- 头部信息区域 -->
          <div class="product-header">
            <div class="header-main">
              <div class="product-id">{{ qrDialog.data.productId }}</div>
              <div class="product-tags">
                <el-tag size="large" :type="statusTagMap[qrDialog.data.status]" effect="light">
                  {{ statusMap[qrDialog.data.status] }}
                </el-tag>
                <el-tag size="large" type="success" effect="plain">
                  {{ processTypeMap[qrDialog.data.processType] }}
                </el-tag>
                <el-tag size="large" type="info" effect="plain">
                  批次号：{{ qrDialog.data.batchNo }}
                </el-tag>
              </div>
            </div>
            <div class="header-meta">
              <div class="meta-item">
                <el-icon><Location /></el-icon>
                <span class="label">生产地点：</span>
                <span class="value">{{ qrDialog.data.location }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span class="label">生产日期：</span>
                <span class="value">{{ qrDialog.data.processTime }}</span>
              </div>
            </div>
          </div>

          <div class="content-wrapper">
            <div class="left-section">
              <div class="qr-section">
                <div class="qr-code-wrapper">
                  <VueQrcode
                    :value="qrContent"
                    :width="320"
                    :margin="0"
                    level="H"
                    class="qrcode-img"
                    :options="{
                      errorCorrectionLevel: 'H',
                      margin: 2,
                      color: {
                        dark: '#303133',
                        light: '#FFFFFF'
                      }
                    }"
                  />
                  <div class="company-logo">
                    <span class="logo-text">🌾</span>
                    <span class="company-name">AgriTrace</span>
                  </div>
                  <div class="qr-tip">
                    <el-icon><Link /></el-icon>
                    <span>扫码查看产品溯源详情</span>
                  </div>
                </div>
                <div class="qr-actions">
                  <el-button-group class="download-group">
                    <el-button type="primary" @click="downloadQR('png')">
                      <el-icon><Picture /></el-icon>下载PNG
                    </el-button>
                    <el-button type="primary" @click="downloadQR('svg')">
                      <el-icon><Document /></el-icon>下载SVG
                    </el-button>
                  </el-button-group>
                </div>
              </div>

              <div class="env-monitor">
                <div class="monitor-header">
                  <span class="title">环境监测数据</span>
                  <el-tag type="success" size="small" effect="plain">实时数据</el-tag>
                </div>
                <div class="monitor-grid">
                  <div class="monitor-item">
                    <span class="icon">🌡️</span>
                    <div class="data">
                      <span class="value">{{ qrDialog.data.temperature }}</span>
                      <span class="label">温度</span>
                    </div>
                  </div>
                  <div class="monitor-item">
                    <span class="icon">💧</span>
                    <div class="data">
                      <span class="value">{{ qrDialog.data.humidity }}</span>
                      <span class="label">湿度</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="right-section">
              <div class="info-section">
                <div class="section-header">
                  <span class="title">生产溯源信息</span>
                </div>
                <div class="info-cards">
                  <div class="info-card">
                    <div class="card-header">生产信息</div>
                    <div class="card-content">
                      <div class="info-item">
                        <span class="label">生产环节</span>
                        <span class="value">{{ qrDialog.data.processName }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">操作人员</span>
                        <span class="value">{{ qrDialog.data.operator }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">操作时间</span>
                        <span class="value">{{ qrDialog.data.processTime }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">生产地点</span>
                        <span class="value">{{ qrDialog.data.location }}</span>
                      </div>
                    </div>
                  </div>
                  <div class="info-card">
                    <div class="card-header">质检信息</div>
                    <div class="card-content">
                      <div class="info-item">
                        <span class="label">质检人员</span>
                        <span class="value">{{ qrDialog.data.inspector }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">质检时间</span>
                        <span class="value">{{ qrDialog.data.inspectTime }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">质检结果</span>
                        <span class="value">
                          <el-tag :type="statusTagMap[qrDialog.data.status]" size="small">
                            {{ statusMap[qrDialog.data.status] }}
                          </el-tag>
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="blockchain-section">
                <div class="section-header">
                  <span class="title">
                    <el-icon><Link /></el-icon>
                    区块链信息 & 溯源链接
                  </span>
                </div>
                <div class="blockchain-content">
                  <div class="hash-info">
                    <div class="hash-display">
                      <el-tooltip :content="qrDialog.blockchainHash" placement="top">
                        <span class="hash-value">{{ shortHash(qrDialog.blockchainHash) }}</span>
                      </el-tooltip>
                      <el-button link type="primary" @click="copyHash">
                        <el-icon><CopyDocument /></el-icon>
                      </el-button>
                    </div>
                    <span class="label">交易哈希</span>
                  </div>
                  <div class="url-info">
                    <div class="url-display">
                      <el-tooltip :content="qrContent" placement="top">
                        <span class="url-value">{{ qrContent }}</span>
                      </el-tooltip>
                      <el-button link type="primary" @click="copyUrl">
                        <el-icon><CopyDocument /></el-icon>
                      </el-button>
                    </div>
                    <span class="label">溯源链接</span>
                  </div>
                  <div class="block-info">
                    <span class="block-height">#{{ blockHeight }}</span>
                    <span class="label">区块高度</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 将验证步骤移到content-wrapper外面 -->
          <div class="verification-section">
            <div class="section-header">
              <span class="title">
                <el-icon><Check /></el-icon>
                流程验证
              </span>
            </div>
            <el-steps :active="3" finish-status="success" align-center>
              <el-step
                v-for="(step, index) in verificationSteps"
                :key="index"
                :title="step.title"
                :description="step.description"
              >
                <template #icon>
                  <component :is="step.icon" />
                </template>
              </el-step>
            </el-steps>
          </div>

          <!-- 底部操作按钮 -->
          <div class="dialog-footer">
            <div class="left-actions">
              <el-button type="success" @click="exportTraceInfo">
                <el-icon><Document /></el-icon>导出溯源证书
              </el-button>
            </div>
            <el-button @click="qrDialog.visible = false">关闭</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted } from 'vue'
  import { Search, Download, Camera, Link, Document, CopyDocument, Location, Calendar, Picture, Check, EditPen, CircleCheck, Checked } from '@element-plus/icons-vue'
  import VueQrcode from 'qrcode.vue'
  import * as XLSX from 'xlsx'
  import { ElMessage } from 'element-plus'
  import html2canvas from 'html2canvas'
  import jsPDF from 'jspdf'
  import { sha256 } from "js-sha256";
  import type { TraceRecord } from '@/types/traceability'
  import { processTypeMap, statusMap, statusTagMap, processIcons, processOptions } from '@/types/traceability'
  import { traceabilityApi } from '@/api/traceability'

  // 组件状态
  const rawData = ref<TraceRecord[]>([])
  const searchParams = reactive({
    productId: '',
    processTypes: [] as string[],
    dateRange: [] as string[]
  })
  const currentPage = ref(1)
  const pageSize = ref(10)
  const loading = ref(false)
  const sortParams = reactive({
    prop: 'processTime',
    order: 'ascending'
  })

  // 二维码相关状态
  const qrDialog = reactive({
    visible: false,
    data: null as TraceRecord | null,
    blockchainHash: ''
  })

  // 统计数据
  const statistics = ref<{
    totalBatches: number
    qualifiedRate: number
    pendingIssues: number
    processTypeStats: {
      [key: string]: number
    }
    statusStats: {
      [key: string]: number
    }
  }>({
    totalBatches: 0,
    qualifiedRate: 0,
    pendingIssues: 0,
    processTypeStats: {},
    statusStats: {}
  })

  // 获取溯源数据
  const fetchTraceData = async () => {
    loading.value = true
    try {
      console.log('开始获取溯源数据...')
      const response = await traceabilityApi.getAllTraceData()
      console.log('溯源数据API响应:', response)
      
      if (response.data.code === 200) {
        console.log('API返回成功，检查数据类型...')
        
        // 检查data是否为数组
        if (!Array.isArray(response.data.data)) {
          console.error('response.data.data不是数组:', {
            type: typeof response.data.data,
            value: response.data.data,
            response: response.data
          })
          console.log('使用模拟数据作为后备')
          useMockData()
          return
        }
        
        console.log('溯源数据获取成功，数据条数:', response.data.data.length)
        rawData.value = response.data.data
        
        // 检查position字段
        const hasPositionData = response.data.data.some((item: TraceRecord) => item.position)
        console.log('数据中包含position字段的记录数:', response.data.data.filter((item: TraceRecord) => item.position).length)
        console.log('是否所有记录都有position字段:', hasPositionData)
        
        // 检查blockchainHash字段
        const hasBlockchainData = response.data.data.some((item: TraceRecord) => item.blockchainHash)
        console.log('数据中包含blockchainHash字段的记录数:', response.data.data.filter((item: TraceRecord) => item.blockchainHash).length)
        console.log('是否所有记录都有blockchainHash字段:', hasBlockchainData)
        
        if (response.data.data.length === 0) {
          console.warn('没有找到溯源数据，使用模拟数据')
          useMockData()
        }
      } else {
        console.error('溯源数据API返回错误:', {
          code: response.data.code,
          message: response.data.message,
          data: response.data.data
        })
        console.log('使用模拟数据作为后备')
        useMockData()
      }
    } catch (error) {
      console.error('获取溯源数据失败:', {
        error: error,
        message: error instanceof Error ? error.message : '未知错误',
        stack: error instanceof Error ? error.stack : undefined,
        timestamp: new Date().toISOString()
      })
      console.log('使用模拟数据作为后备')
      useMockData()
    } finally {
      loading.value = false
      console.log('溯源数据获取完成，loading状态:', loading.value)
    }
  }

  // 使用模拟数据
  const useMockData = () => {
    console.log('加载模拟数据')
    const mockData: TraceRecord[] = [
      {
        id: 'mock_001',
        productId: 'PROD_2024001',
        batchNo: 'BATCH_001',
        processType: 'planting',
        processName: '种植环节',
        processTime: '2024-01-15 08:30:00',
        operator: '张三',
        location: '广东省广州市天河区',
        position: [113.3612, 23.1246],
        status: 'qualified',
        temperature: '25.5°C',
        humidity: '65%',
        inspector: '李四',
        inspectTime: '2024-01-15 16:00:00',
        description: '春季水稻种植，环境适宜',
        blockchainHash: '0x1234567890abcdef1234567890abcdef12345678'
      },
      {
        id: 'mock_002',
        productId: 'PROD_2024002',
        batchNo: 'BATCH_002',
        processType: 'growing',
        processName: '培育环节',
        processTime: '2024-01-20 10:00:00',
        operator: '李四',
        location: '广东省深圳市南山区',
        position: [113.9294, 22.5333],
        status: 'qualified',
        temperature: '26.2°C',
        humidity: '68%',
        inspector: '王五',
        inspectTime: '2024-01-20 17:30:00',
        description: '水稻生长管理，定期施肥浇水',
        blockchainHash: '0xabcdef1234567890abcdef1234567890abcdef12'
      },
      {
        id: 'mock_003',
        productId: 'PROD_2024003',
        batchNo: 'BATCH_003',
        processType: 'harvest',
        processName: '采收环节',
        processTime: '2024-04-15 14:30:00',
        operator: '王五',
        location: '广东省东莞市',
        position: [113.7518, 23.0207],
        status: 'qualified',
        temperature: '28.1°C',
        humidity: '72%',
        inspector: '赵六',
        inspectTime: '2024-04-15 18:00:00',
        description: '水稻收获，质量检测合格',
        blockchainHash: '0x567890abcdef1234567890abcdef1234567890ab'
      },
      {
        id: 'mock_004',
        productId: 'PROD_2024004',
        batchNo: 'BATCH_004',
        processType: 'processing',
        processName: '加工环节',
        processTime: '2024-04-20 09:00:00',
        operator: '赵六',
        location: '广东省佛山市',
        position: [113.1224, 23.0094],
        status: 'qualified',
        temperature: '22.5°C',
        humidity: '45%',
        inspector: '钱七',
        inspectTime: '2024-04-20 16:00:00',
        description: '稻谷加工，脱壳包装',
        blockchainHash: '0x890abcdef1234567890abcdef1234567890abcdef'
      },
      {
        id: 'mock_005',
        productId: 'PROD_2024005',
        batchNo: 'BATCH_005',
        processType: 'transport',
        processName: '运输环节',
        processTime: '2024-04-25 16:00:00',
        operator: '钱七',
        location: '广东省珠海市',
        position: [113.5767, 22.2707],
        status: 'qualified',
        temperature: '24.8°C',
        humidity: '58%',
        inspector: '孙八',
        inspectTime: '2024-04-25 20:00:00',
        description: '产品运输，冷链配送',
        blockchainHash: '0xcdef1234567890abcdef1234567890abcdef1234'
      }
    ]
    
    rawData.value = mockData
    console.log('模拟数据加载完成，数据条数:', mockData.length)
  }

  // 获取统计数据
  const fetchStatistics = async () => {
    try {
      console.log('开始获取统计数据...')
      const response = await traceabilityApi.getTraceStatistics()
      console.log('统计数据API响应:', response)
      
      if (response.data.code === 200) {
        console.log('统计数据获取成功:', response.data.data)
        statistics.value = response.data.data
      } else {
        console.error('统计数据API返回错误:', {
          code: response.data.code,
          message: response.data.message,
          data: response.data.data
        })
        console.log('使用模拟统计数据作为后备')
        useMockStatistics()
      }
    } catch (error) {
      console.error('获取统计数据失败:', {
        error: error,
        message: error instanceof Error ? error.message : '未知错误',
        stack: error instanceof Error ? error.stack : undefined,
        timestamp: new Date().toISOString()
      })
      console.log('使用模拟统计数据作为后备')
      useMockStatistics()
    }
  }

  // 使用模拟统计数据
  const useMockStatistics = () => {
    console.log('加载模拟统计数据')
    statistics.value = {
      totalBatches: 1250,
      qualifiedRate: 98.5,
      pendingIssues: 12,
      processTypeStats: {
        planting: 250,
        growing: 250,
        harvest: 250,
        processing: 250,
        transport: 250
      },
      statusStats: {
        qualified: 1231,
        unqualified: 7,
        pending: 12
      }
    }
    console.log('模拟统计数据加载完成:', statistics.value)
  }

  // 计算属性
  const filteredData = computed(() => {
    return rawData.value.filter(item => {
      const matchesID = item.productId.includes(searchParams.productId.trim())
      const matchesProcess = searchParams.processTypes.length === 0 ||
        searchParams.processTypes.includes(item.processType)
      const [start, end] = searchParams.dateRange
      const itemDate = new Date(item.processTime).getTime()
      const startDate = start ? new Date(start).getTime() : 0
      const endDate = end ? new Date(end).getTime() + 86400000 : Infinity

      return matchesID && matchesProcess && (itemDate >= startDate) && (itemDate <= endDate)
    }).sort((a, b) => {
      const sortKey = sortParams.prop as keyof TraceRecord
      const aValue = a[sortKey]
      const bValue = b[sortKey]
      
      if (aValue === undefined || bValue === undefined) return 0
      
      return sortParams.order === 'ascending'
        ? aValue > bValue ? 1 : -1
        : aValue < bValue ? 1 : -1
    })
  })

  const pagedData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    return filteredData.value.slice(start, start + pageSize.value)
  })

  // 统计卡片数据 - 使用后端统计数据
  const totalBatches = computed(() => statistics.value.totalBatches)
  const qualifiedRate = computed(() => statistics.value.qualifiedRate.toFixed(1))
  const pendingIssues = computed(() => statistics.value.pendingIssues)

  // 二维码内容
  const qrContent = computed(() => {
    if (!qrDialog.data) return ''
    
    // 构建RESTful风格的URL，使用产品ID作为路径参数
    const url = `http://192.144.214.228:45995/blocktest/productid/${qrDialog.data.productId}`
    
    console.log('生成的二维码URL:', url)
    console.log('产品ID:', qrDialog.data.productId)
    
    return url
  })

  // 方法
  const handleSearch = () => {
    currentPage.value = 1
  }

  const resetSearch = () => {
    searchParams.productId = ''
    searchParams.processTypes = []
    searchParams.dateRange = []
    handleSearch()
  }

  const handleSortChange = ({ prop, order }: any) => {
    sortParams.prop = prop
    sortParams.order = order
  }

  const showQRDialog = async (row: TraceRecord) => {
    console.log("溯源码启动！");
    console.log("当前行数据:", row);
    qrDialog.data = row
    console.log("溯源码启动！2");
    
    // 直接使用从traceability/all接口获取的blockchainHash
    if (row.blockchainHash) {
      console.log('使用从API获取的区块链哈希:', row.blockchainHash)
      qrDialog.blockchainHash = row.blockchainHash
    } else {
      console.log('API数据中没有区块链哈希，使用本地生成')
      try {
        const jsonStr = JSON.stringify(row)
        qrDialog.blockchainHash = sha256(jsonStr)
        console.log('本地生成的区块链哈希:', qrDialog.blockchainHash)
      } catch (err) {
        console.error('生成区块链哈希失败:', {
          error: err,
          message: err instanceof Error ? err.message : '未知错误',
          stack: err instanceof Error ? err.stack : undefined,
          productId: row.productId,
          timestamp: new Date().toISOString()
        })
        qrDialog.blockchainHash = "NaN"
        console.log('设置默认区块链哈希为NaN')
      }
    }
    
    console.log("溯源码启动！3");
    console.log('打开二维码对话框，数据:', qrDialog.data)
    
    // 测试生成的URL格式
    setTimeout(() => {
      console.log('生成的完整URL:', qrContent.value)
      console.log('URL长度:', qrContent.value.length)
      console.log('URL是否有效:', qrContent.value.startsWith('http://172.17.91.81:9095/blocktest/productid/'))
      
      // 提取产品ID
      const productId = qrContent.value.split('/').pop()
      console.log('URL中的产品ID:', productId)
      console.log('产品ID是否匹配:', productId === qrDialog.data?.productId)
    }, 100)
    
    qrDialog.visible = true
  }

  const downloadQR = async (type: 'png' | 'svg') => {
    console.log('开始下载二维码，类型:', type)
    const qrWrapper = document.querySelector('.qr-code-wrapper')
    if (!qrWrapper) {
      console.error('未找到二维码包装元素')
      return
    }

    try {
      if (type === 'png') {
        console.log('开始生成PNG格式二维码')
        const canvas = await html2canvas(qrWrapper as HTMLElement, {
          backgroundColor: '#FFFFFF',
          scale: 2
        })
        console.log('PNG画布生成成功，尺寸:', canvas.width, 'x', canvas.height)

        const link = document.createElement('a')
        link.download = `溯源二维码_${qrDialog.data?.productId || 'code'}.png`
        link.href = canvas.toDataURL('image/png')
        link.click()
        console.log('PNG二维码下载完成，文件名:', link.download)
      } else {
        console.log('开始生成SVG格式二维码')
        const svgElement = qrWrapper.querySelector('svg')
        if (!svgElement) {
          console.error('未找到SVG元素')
          return
        }

        const svgData = new XMLSerializer().serializeToString(svgElement)
        const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' })
        const link = document.createElement('a')
        link.download = `溯源二维码_${qrDialog.data?.productId || 'code'}.svg`
        link.href = URL.createObjectURL(svgBlob)
        link.click()
        URL.revokeObjectURL(link.href)
        console.log('SVG二维码下载完成，文件名:', link.download)
      }
      ElMessage.success('下载成功')
    } catch (error) {
      console.error('二维码下载失败:', {
        error: error,
        message: error instanceof Error ? error.message : '未知错误',
        stack: error instanceof Error ? error.stack : undefined,
        type: type,
        productId: qrDialog.data?.productId,
        timestamp: new Date().toISOString()
      })
      ElMessage.error('下载失败')
    }
  }

  const handleExport = async () => {
    console.log('开始导出溯源数据')
    try {
      const params = {
        productId: searchParams.productId || undefined,
        processType: searchParams.processTypes.join(',') || undefined,
        status: undefined,
        startDate: searchParams.dateRange[0] || undefined,
        endDate: searchParams.dateRange[1] || undefined,
        format: 'excel' as const
      }
      console.log('导出参数:', params)
      
      const response = await traceabilityApi.exportTraceData(params)
      console.log('导出API响应:', response)
      
      const blob = new Blob([response.data], { 
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
      })
      console.log('导出文件Blob创建成功，大小:', blob.size, 'bytes')
      
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `溯源数据_${new Date().toLocaleDateString()}.xlsx`
      link.click()
      window.URL.revokeObjectURL(url)
      console.log('溯源数据导出完成，文件名:', link.download)
      ElMessage.success('导出成功')
    } catch (error) {
      console.error('导出失败:', {
        error: error,
        message: error instanceof Error ? error.message : '未知错误',
        stack: error instanceof Error ? error.stack : undefined,
        searchParams: searchParams,
        timestamp: new Date().toISOString()
      })
      ElMessage.error('导出失败')
    }
  }

  // 初始化
  onMounted(async () => {
    await Promise.all([
      fetchTraceData(),
      fetchStatistics()
    ])
  })

  // 辅助函数
  const shortHash = (hash: string) => hash ? `${hash.slice(0, 8)}...${hash.slice(-8)}` : ''
  const blockHeight = computed(() => Math.floor(Math.random() * 1000000))

  // 通用复制函数
  const copyToClipboard = (text: string, itemName: string) => {
    console.log(`开始复制${itemName}`)
    if (!text) {
      console.error(`${itemName}为空，无法复制`)
      ElMessage.error(`${itemName}为空`)
      return
    }

    try {
      // 检查navigator.clipboard是否可用
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text)
        console.log(`${itemName}复制成功:`, text)
        ElMessage.success('已复制到剪贴板')
      } else {
        // 后备方案：使用传统的document.execCommand
        console.log('navigator.clipboard不可用，使用后备方案')
        const textArea = document.createElement('textarea')
        textArea.value = text
        textArea.style.position = 'fixed'
        textArea.style.left = '-999999px'
        textArea.style.top = '-999999px'
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        
        const successful = document.execCommand('copy')
        document.body.removeChild(textArea)
        
        if (successful) {
          console.log(`${itemName}复制成功(后备方案):`, text)
          ElMessage.success('已复制到剪贴板')
        } else {
          throw new Error('document.execCommand复制失败')
        }
      }
    } catch (error) {
      console.error(`复制${itemName}失败:`, {
        error: error,
        message: error instanceof Error ? error.message : '未知错误',
        stack: error instanceof Error ? error.stack : undefined,
        text: text,
        timestamp: new Date().toISOString(),
        navigatorClipboard: !!navigator.clipboard,
        documentExecCommand: !!document.execCommand
      })
      
      // 最后的后备方案：显示内容让用户手动复制
      ElMessage({
        message: `复制失败，请手动复制${itemName}: ${text}`,
        type: 'warning',
        duration: 5000,
        showClose: true
      })
    }
  }

  // 添加新方法
  const copyHash = () => {
    copyToClipboard(qrDialog.blockchainHash, '区块链哈希')
  }

  const copyUrl = () => {
    copyToClipboard(qrContent.value, '溯源链接')
  }

  const exportTraceInfo = async () => {
    console.log('开始导出溯源证书')
    if (!qrDialog.data) {
      console.error('溯源数据为空，无法导出证书')
      return
    }

    try {
      console.log('创建证书HTML内容')
      // 使用 html2canvas 将内容转换为图片
      const content = document.createElement('div')
      content.innerHTML = `
        <div style="padding: 40px; font-family: system-ui, -apple-system, sans-serif;">
          <h1 style="text-align: center; margin-bottom: 30px;">产品溯源证书</h1>
          <div style="display: grid; grid-template-columns: 1fr 200px; gap: 20px;">
            <div>
              <h2 style="color: #409eff; font-size: 16px; margin-bottom: 15px;">基本信息</h2>
              <p>产品ID：${qrDialog.data.productId}</p>
              <p>批次号：${qrDialog.data.batchNo || '-'}</p>
              <p>生产地点：${qrDialog.data.location || '-'}</p>
              <p>生产日期：${qrDialog.data.processTime}</p>

              <h2 style="color: #409eff; font-size: 16px; margin: 20px 0 15px;">生产信息</h2>
              <p>生产环节：${qrDialog.data.processName}</p>
              <p>操作人员：${qrDialog.data.operator}</p>
              <p>环境温度：${qrDialog.data.temperature || '-'}</p>
              <p>环境湿度：${qrDialog.data.humidity || '-'}</p>

              <h2 style="color: #409eff; font-size: 16px; margin: 20px 0 15px;">质检信息</h2>
              <p>质检人员：${qrDialog.data.inspector || '-'}</p>
              <p>质检时间：${qrDialog.data.inspectTime || '-'}</p>
              <p>质检结果：${statusMap[qrDialog.data.status as keyof typeof statusMap]}</p>

              <h2 style="color: #409eff; font-size: 16px; margin: 20px 0 15px;">区块链信息</h2>
              <p>交易哈希：${qrDialog.blockchainHash}</p>
              <p>区块高度：#${blockHeight.value}</p>
            </div>
            <div id="qr-container"></div>
          </div>
          <div style="margin-top: 30px; text-align: center; color: #909399; font-size: 12px;">
            生成时间：${new Date().toLocaleString()}
          </div>
        </div>
      `

      console.log('复制二维码到证书内容')
      // 复制二维码
      const qrOriginal = document.querySelector('.qrcode-img canvas')
      if (qrOriginal) {
        const qrContainer = content.querySelector('#qr-container')
        if (qrContainer) {
          const qrClone = qrOriginal.cloneNode(true) as HTMLCanvasElement
          qrClone.style.width = '200px'
          qrClone.style.height = '200px'
          qrContainer.appendChild(qrClone)
          console.log('二维码复制成功')
        } else {
          console.error('未找到二维码容器元素')
        }
      } else {
        console.error('未找到原始二维码画布')
      }

      document.body.appendChild(content)
      console.log('证书内容已添加到DOM')

      console.log('开始生成证书画布')
      const canvas = await html2canvas(content, {
        scale: 2,
        backgroundColor: '#ffffff'
      })
      console.log('证书画布生成成功，尺寸:', canvas.width, 'x', canvas.height)

      document.body.removeChild(content)
      console.log('证书内容已从DOM移除')

      // 将画布转换为PDF
      console.log('开始生成PDF')
      const imgData = canvas.toDataURL('image/jpeg', 1.0)
      const pdf = new jsPDF({
        orientation: 'portrait',
        unit: 'mm',
        format: 'a4'
      })

      const imgWidth = 210
      const pageHeight = 297
      const imgHeight = canvas.height * imgWidth / canvas.width
      let heightLeft = imgHeight
      let position = 0

      pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight)
      heightLeft -= pageHeight

      while (heightLeft >= 0) {
        position = heightLeft - imgHeight
        pdf.addPage()
        pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight)
        heightLeft -= pageHeight
      }

      const fileName = `溯源证书_${qrDialog.data.productId}.pdf`
      pdf.save(fileName)
      console.log('溯源证书PDF生成完成，文件名:', fileName)
      ElMessage.success('证书导出成功')
    } catch (error) {
      console.error('PDF生成错误:', {
        error: error,
        message: error instanceof Error ? error.message : '未知错误',
        stack: error instanceof Error ? error.stack : undefined,
        productId: qrDialog.data?.productId,
        timestamp: new Date().toISOString()
      })
      ElMessage.error('证书导出失败')
    }
  }

  // 验证步骤数据
  const verificationSteps = computed(() => {
    if (!qrDialog.data) return []
    return [
      {
        title: '数据采集',
        description: `${qrDialog.data.operator} - ${qrDialog.data.processTime}`,
        icon: EditPen
      },
      {
        title: '区块链存证',
        description: `区块高度: #${blockHeight.value}`,
        icon: CircleCheck
      },
      {
        title: '质量验证',
        description: `${qrDialog.data.inspector} - ${qrDialog.data.inspectTime}`,
        icon: Checked
      }
    ]
  })
  </script>

  <style lang="scss" scoped>
  .trace-container {
    padding: 14px;

    // 统计卡片
    .dashboard-cards {
      display: grid;
      gap: 20px;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      margin-bottom: 10px;

      .stat-card {
        border: none;
        border-radius: 12px;
        transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);

        &:hover {
          transform: translateY(-3px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        .card-content {
          display: flex;
          align-items: center;
          padding: 0 16px;

          .card-icon {
            width: 56px;
            height: 56px;
            border-radius: 12px;
            margin-right: 16px;
            background-size: 55%;
            background-position: center;
            background-repeat: no-repeat;

            &.process {
              background-color: rgba(101, 184, 89, 0.1);
              background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%2367C23A' d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.29c2.49.4 4.43 2.54 4.43 5.29c0 2.24-1.29 4.17-3.15 5.1'/%3E%3C/svg%3E");
            }

            &.quality {
              background-color: rgba(64, 158, 255, 0.1);
              background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%23409EFF' d='M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2m-2 15l-5-5l1.41-1.41L10 14.17l7.59-7.59L19 8z'/%3E%3C/svg%3E");
            }

            &.alert {
              background-color: rgba(245, 108, 108, 0.1);
              background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%23F56C6C' d='M12 2c1.1 0 2 .9 2 2v10c0 1.1-.9 2-2 2s-2-.9-2-2V4c0-1.1.9-2 2-2m-1 18c0 .55.45 1 1 1s1-.45 1-1s-.45-1-1-1s-1 .45-1 1'/%3E%3C/svg%3E");
            }
          }

          .card-text {
            .card-title {
              color: #606266;
              font-size: 14px;
              margin-bottom: 4px;
            }

            .card-value {
              font-size: 28px;
              font-weight: 700;
              letter-spacing: 0.5px;
            }
          }
        }
      }
    }

    // 高级搜索
    .advanced-search {
      border-radius: 12px;
      padding: 16px;
      margin-bottom: 10px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

      .el-form {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
        gap: 12px;

        .el-form-item {
          margin: 0;

          :deep(.el-input__wrapper) {
            border-radius: 8px;
          }

          .el-select {
            width: 100%;
          }
        }

        .el-button {
          padding: 8px 20px;
          border-radius: 8px;
          transition: all 0.2s ease;

          &:hover {
            transform: translateY(-1px);
          }
        }
      }
    }

    // 数据表格
    .data-table {
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

      :deep(.el-table) {

        th {
          font-weight: 600;
        }

        td {
          .process-tag {
            display: flex;
            align-items: center;
            gap: 8px;

            .tag-icon {
              display: inline-block;
              width: 24px;
              height: 24px;
              line-height: 24px;
              text-align: center;
              border-radius: 4px;
              margin-right: 8px;
            }
          }

          .quality-status {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 10px;
            border-radius: 16px;
            font-size: 13px;

            .status-dot {
              display: inline-block;
            }

            &.qualified .status-dot {
              background-color: #67c23a;
            }
            &.unqualified .status-dot {
              background-color: #f56c6c;
            }
            &.pending .status-dot {
              background-color: #e6a23c;
            }
          }

          .el-button {
            padding: 6px 12px;
            font-size: 13px;
          }
        }
      }

      .pagination-wrapper {
        padding: 16px;
      }
    }

    // 增强型二维码弹窗
    .trace-dialog {
      :deep(.el-dialog__body) {
        padding: 0;
        max-height: 85vh;
        overflow-y: auto;
      }

      :deep(.el-dialog__header) {
        margin: 0;
        padding: 20px 24px;
        border-bottom: 1px solid #e4e7ed;

        .el-dialog__title {
          font-size: 18px;
          font-weight: 600;
        }
      }

      :deep(.el-dialog) {
        max-height: 95vh;
        display: flex;
        flex-direction: column;
      }
    }

    .qr-dialog-content {
      max-height: calc(85vh - 120px);
      overflow-y: auto;
      padding: 0;

      .product-header {
        padding: 20px 24px;
        border-bottom: 1px solid #f0f0f0;

        .header-main {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;

          .product-id {
            font-size: 24px;
            font-weight: 600;
            letter-spacing: 0.5px;
          }

          .product-tags {
            display: flex;
            gap: 8px;
          }
        }

        .header-meta {
          display: flex;
          gap: 24px;

          .meta-item {
            display: flex;
            align-items: center;
            gap: 6px;
            color: #606266;
            font-size: 14px;

            .el-icon {
              color: #909399;
              font-size: 16px;
            }
          }
        }
      }

      .content-wrapper {
        display: grid;
        grid-template-columns: 380px 1fr;
        gap: 24px;
        padding: 24px;
        min-height: 450px;
      }

      .left-section {
        .qr-section {
          border-radius: 12px;
          padding: 24px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
          margin-bottom: 24px;

          .qr-code-wrapper {
            padding: 28px;
            border-radius: 8px;
            text-align: center;
            margin-bottom: 20px;

            .qrcode-img {
              filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.1));
            }

            .company-logo {
              margin-top: 20px;
              padding-top: 20px;
              border-top: 1px dashed #e4e7ed;
              display: flex;
              align-items: center;
              justify-content: center;
              gap: 8px;

              .logo-text {
                font-size: 24px;
                line-height: 1;
              }

              .company-name {
                font-size: 16px;
                font-weight: 600;
                background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
              }
            }

            .qr-tip {
              margin-top: 16px;
              padding: 10px 16px;
              background: rgba(64, 158, 255, 0.1);
              border: 1px solid rgba(64, 158, 255, 0.2);
              border-radius: 6px;
              display: flex;
              align-items: center;
              justify-content: center;
              gap: 6px;
              font-size: 13px;
              color: #409eff;

              .el-icon {
                font-size: 14px;
              }
            }
          }

          .qr-actions {
            margin-top: 20px;

            .download-group {
              display: flex;
              gap: 12px;
              justify-content: center;

              .el-button {
                flex: 1;
                padding: 12px 24px;
                font-size: 14px;
                border-radius: 8px;
                transition: all 0.3s ease;

                &:hover {
                  transform: translateY(-2px);
                  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                }

                .el-icon {
                  margin-right: 6px;
                  font-size: 16px;
                }

                &:first-child {
                  background: linear-gradient(135deg, #409eff 0%, #53a8ff 100%);
                  border: none;
                }

                &:last-child {
                  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
                  border: none;
                }
              }
            }
          }
        }

        .env-monitor {
          border-radius: 12px;
          padding: 24px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

          .monitor-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;

            .title {
              font-size: 16px;
              font-weight: 600;
            }
          }

          .monitor-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 16px;

            .monitor-item {
              padding: 20px;
              border-radius: 8px;
              display: flex;
              align-items: center;
              gap: 12px;
              transition: all 0.3s ease;

              &:hover {
                transform: translateY(-2px);
                box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
              }

              .icon {
                font-size: 28px;
              }

              .data {
                .value {
                  display: block;
                  font-size: 22px;
                  font-weight: 600;
                  line-height: 1.2;
                }

                .label {
                  font-size: 13px;
                  color: #909399;
                }
              }
            }
          }
        }
      }

      .right-section {
        display: flex;
        flex-direction: column;
        gap: 24px;
        max-height: 550px;
        overflow-y: auto;

        > div {
          border-radius: 12px;
          padding: 24px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
        }

        .section-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 20px;
          padding-bottom: 12px;
          border-bottom: 2px solid #e4e7ed;

          .title {
            font-size: 16px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 6px;

            .el-icon {
              color: #409eff;
            }
          }
        }

        .info-cards {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 20px;

          .info-card {
            border-radius: 8px;
            padding: 20px;
            transition: all 0.3s ease;
            border: 1px solid #c4c7cc;
            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
            }

            .card-header {
              font-weight: 600;
              color: #409eff;
              margin-bottom: 16px;
              font-size: 15px;
            }

            .info-item {
              display: flex;
              justify-content: space-between;
              padding: 10px 0;
              border-bottom: 1px dashed #e4e7ed;

              &:last-child {
                border-bottom: none;
              }

              .label {
                color: #909399;
                font-size: 14px;
              }

              .value {
                font-weight: 500;
                font-size: 14px;
              }
            }
          }
        }

        .blockchain-section {
          .blockchain-content {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;

            > div {
              border-radius: 8px;
              padding: 24px;
              text-align: center;
              transition: all 0.3s ease;

              &:hover {
                transform: translateY(-2px);
                box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
              }

              .hash-display {
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 8px;
                margin-bottom: 12px;

                .hash-value {
                  font-family: monospace;
                  font-size: 16px;
                  color: #409eff;
                  cursor: pointer;
                  padding: 6px 10px;
                  background: rgba(64, 158, 255, 0.1);
                  border-radius: 4px;
                }
              }

              .url-display {
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 8px;
                margin-bottom: 12px;

                .url-value {
                  font-family: monospace;
                  font-size: 12px;
                  color: #67c23a;
                  cursor: pointer;
                  padding: 6px 10px;
                  background: rgba(103, 194, 58, 0.1);
                  border-radius: 4px;
                  max-width: 200px;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                  display: block;
                }
              }

              .block-height {
                font-size: 28px;
                font-weight: 600;
                display: block;
                margin-bottom: 12px;
              }

              .label {
                color: #909399;
                font-size: 13px;
              }
            }
          }
        }
      }
    }

    .verification-section {
      padding: 28px 24px;
      border-top: 1px solid #f0f0f0;

      .section-header {

        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 28px;
        padding-bottom: 12px;
        border-bottom: 2px solid #e4e7ed;

        .title {
          font-size: 16px;
          font-weight: 600;
          display: flex;
          align-items: center;
          gap: 6px;

          .el-icon {
            color: #409eff;
          }
        }
      }

      :deep(.el-steps) {
        padding: 0 40px;

        .el-step {
          &.is-horizontal {
            .el-step__line {
              height: 2px;
              top: 15px;
            }
          }

          .el-step__head {
            .el-step__icon {
              width: 32px;
              height: 32px;
              font-size: 16px;
              transition: all 0.3s ease;

              &.is-text {
                border-color: #409eff;
                color: #409eff;
              }
            }

            &.is-success {
              .el-step__icon {
                border-color: #67c23a;
                color: #67c23a;
              }
            }

            &.is-process {
              .el-step__icon {
                border-color: #409eff;
                color: #409eff;
              }
            }
          }

          .el-step__main {
            .el-step__title {
              font-size: 15px;
              font-weight: 500;
              line-height: 1.4;
              margin-top: 8px;

              &.is-success {
                color: #67c23a;
              }

              &.is-process {
                color: #409eff;
                font-weight: 600;
              }
            }

            .el-step__description {
              font-size: 13px;
              color: #909399;
              margin-top: 4px;
            }
          }

          &.is-success {
            .el-step__line {
              background-color: #67c23a;
            }
          }
        }
      }
    }

    .dialog-footer {
      padding: 20px 24px;
      border-top: 1px solid #e4e7ed;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: #fafafa;

      .el-button {
        padding: 12px 24px;
        font-size: 14px;

        .el-icon {
          margin-right: 4px;
        }
      }
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    .trace-container {
      padding: 16px;

      .dashboard-cards {
        grid-template-columns: 1fr;
      }

      .advanced-search {
        .el-form {
          grid-template-columns: 1fr;
        }
      }

      .data-table {
        :deep(.el-table) {
          .el-table__body-wrapper {
            overflow-x: auto;
          }
          
          // 在移动端隐藏一些次要列
          .el-table__header-wrapper,
          .el-table__body-wrapper {
            th:nth-child(4), // 生产地点
            td:nth-child(4),
            th:nth-child(6), // 负责人
            td:nth-child(6),
            th:nth-child(7), // 质检员
            td:nth-child(7) {
              display: none;
            }
          }
        }
      }
    }

    // 二维码弹窗响应式
    .trace-dialog {
      :deep(.el-dialog) {
        width: 95% !important;
        max-width: 95vw;
        margin: 2vh auto;
        max-height: 96vh;
      }

      :deep(.el-dialog__body) {
        max-height: 90vh;
      }

      .qr-dialog-content {
        max-height: calc(90vh - 120px);

        .content-wrapper {
          grid-template-columns: 1fr;
          gap: 20px;
          padding: 20px;
          min-height: auto;
        }

        .left-section {
          .qr-section {
            .qr-code-wrapper {
              padding: 20px;
              
              .qrcode-img {
                width: 240px !important;
              }
            }
          }
        }

        .right-section {
          max-height: none;
          overflow-y: visible;

          .info-cards {
            grid-template-columns: 1fr;
            gap: 16px;
          }

          .blockchain-section {
            .blockchain-content {
              grid-template-columns: 1fr;
              gap: 16px;
            }
          }
        }

        .verification-section {
          padding: 20px 20px;

          :deep(.el-steps) {
            padding: 0 20px;
          }
        }
      }
    }
  }

  @media (max-width: 480px) {
    .trace-container {
      .data-table {
        :deep(.el-table) {
          // 在更小的屏幕上隐藏更多列
          .el-table__header-wrapper,
          .el-table__body-wrapper {
            th:nth-child(2), // 批次号
            td:nth-child(2),
            th:nth-child(8), // 环境数据
            td:nth-child(8) {
              display: none;
            }
          }
        }
      }
    }

    // 小屏幕二维码弹窗优化
    .trace-dialog {
      :deep(.el-dialog) {
        width: 98% !important;
        margin: 1vh auto;
        max-height: 98vh;
      }

      :deep(.el-dialog__body) {
        max-height: 92vh;
      }

      .qr-dialog-content {
        max-height: calc(92vh - 120px);

        .product-header {
          padding: 16px;

          .header-main {
            flex-direction: column;
            gap: 12px;
            align-items: flex-start;

            .product-tags {
              flex-wrap: wrap;
            }
          }

          .header-meta {
            flex-direction: column;
            gap: 8px;
          }
        }

        .content-wrapper {
          padding: 16px;
          gap: 16px;
        }

        .left-section {
          .qr-section {
            padding: 16px;

            .qr-code-wrapper {
              padding: 16px;
              
              .qrcode-img {
                width: 200px !important;
              }
            }

            .qr-actions {
              .download-group {
                flex-direction: column;
                gap: 8px;

                .el-button {
                  width: 100%;
                }
              }
            }
          }

          .env-monitor {
            padding: 16px;

            .monitor-grid {
              grid-template-columns: 1fr;
            }
          }
        }

        .right-section {
          gap: 16px;

          > div {
            padding: 16px;
          }

          .info-cards {
            gap: 12px;

            .info-card {
              padding: 12px;

              .info-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 4px;
              }
            }
          }

          .blockchain-section {
            .blockchain-content {
              gap: 12px;

              > div {
                padding: 16px;
              }
            }
          }
        }

        .verification-section {
          padding: 16px;

          :deep(.el-steps) {
            padding: 0 10px;
          }
        }

        .dialog-footer {
          padding: 16px;
          flex-direction: column;
          gap: 12px;

          .left-actions {
            width: 100%;
          }

          .el-button {
            width: 100%;
          }
        }
      }
    }
  }

  // 添加表格环境数据样式
  .env-data {
    display: flex;
    gap: 12px;

    .env-item {
      font-size: 13px;
      color: #606266;
      display: flex;
      align-items: center;
      gap: 4px;
    }
  }

  // 修改相关样式
  .company-logo {
    margin-top: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;

    .logo-text {
      font-size: 24px;
      line-height: 1;
    }

    .company-name {
      font-size: 16px;
      font-weight: 600;
      background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
  }
  </style>
